<?php

namespace Cake\Controller\Component;

use Cake\Routing\Router;
use Cake\Controller\Component;

class UrlComponent extends Component {

    public function urlWithReturnUrl($request, array $url = NULL, $full = false, $keepCurrentUrl = true) {
        if (!$keepCurrentUrl && isset($request->query['returnUrl'])) {
            $returnUrl = $request->query['returnUrl'];
        } else {
            $returnUrl = $request->here;
        }

        if ($url == null) {
            $url = array('?' => ['returnUrl' => $returnUrl]);
        } else if (!isset($url['?'])) {
            $url['?'] = ['returnUrl' => $returnUrl];
        } else {
            array_push($url['?'], ['returnUrl' => $returnUrl]);
        }

        return Router::url($url, $full);
    }

    public function hasReturnUrl($request) {
        return isset($request->query['returnUrl']) && !empty($request->query['returnUrl']);
    }

    public function returnUrl($request, array $url, $full = false) {
        if ($this->hasReturnUrl($request)) {
            $paths = split('/', $request->query['returnUrl']);
            array_shift($paths);
            if (strpos($request->query['returnUrl'], '/') === 0) {
                array_shift($paths);
            }
            return '/'.implode('/', $paths);
        }

        return Router::url($url, $full);
    }

}
